package com.micro.ai.commons.config;

import com.micro.ai.commons.util.RequestUtils;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;

/**
 * Feign 配置类
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Configuration
public class FeignConfig {

    /**
     * Feign 日志级别配置
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.BASIC;
    }

    /**
     * Feign 请求拦截器 - 传递请求头和服务信息
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    
                    // 传递请求ID
                    String requestId = RequestUtils.getRequestId();
                    if (requestId != null) {
                        template.header("X-Request-Id", requestId);
                    }
                    
                    // 传递用户ID
                    Long userId = RequestUtils.getUserId();
                    if (userId != null) {
                        template.header("X-User-Id", userId.toString());
                    }
                    
                    // 传递租户ID
                    String tenantId = RequestUtils.getTenantId();
                    if (tenantId != null) {
                        template.header("X-Tenant-Id", tenantId);
                    }
                    
                    // 传递服务名
                    template.header("X-Service-Name", "micro-ai-commons");
                    
                    // 传递 Authorization 头
                    String authorization = request.getHeader("Authorization");
                    if (authorization != null) {
                        template.header("Authorization", authorization);
                    }
                    
                    // 传递其他必要的请求头
                    String userAgent = request.getHeader("User-Agent");
                    if (userAgent != null) {
                        template.header("User-Agent", userAgent);
                    }
                    
                    String contentType = request.getHeader("Content-Type");
                    if (contentType != null) {
                        template.header("Content-Type", contentType);
                    }
                }
            }
        };
    }

    /**
     * Feign 错误解码器
     */
    @Bean
    public ErrorDecoder errorDecoder() {
        return new ErrorDecoder() {
            @Override
            public Exception decode(String methodKey, feign.Response response) {
                String message = String.format("Feign调用失败: %s, 状态码: %d", methodKey, response.status());
                
                log.error("Feign调用失败: methodKey={}, status={}, reason={}", 
                    methodKey, response.status(), response.reason());
                
                return new RuntimeException(message);
            }
        };
    }
}
